package ai.people.core.grpc.utils;

import ai.people.netmon.framework.exception.enums.CommonEnum;
import ai.people.netmon.framework.exception.type.BusinessException;
import com.alibaba.fastjson.JSON;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * proto json互转
 *
 * @author yuanqinglong
 * @date 2022/6/5 14:56
 */
public class ProtoJsonUtil {
    private static final Logger logger = LoggerFactory.getLogger(ProtoJsonUtil.class);

    /**
     * proto 对象转 JSON
     * <p>
     * String jsonObject = ProtoJsonUtil.toJson(user1);
     *
     * @param sourceMessage proto 对象
     * @return 返回 JSON 数据
     */
    public static String toJson(Message sourceMessage) {
        if (sourceMessage != null) {
            try {
                return JsonFormat.printer().includingDefaultValueFields().print(sourceMessage);
            } catch (InvalidProtocolBufferException e) {
                logger.error("ProtoMessage to JSON error:", e);
                throw new BusinessException(CommonEnum.DATA_CONVERSION_EXCEPTION);
            }
        }
        return null;
    }

    /**
     * java
     * proto 对象转 java对象
     *
     * @param sourceMessage proto 对象
     * @param clazz         clazz
     * @return 返回 JSON 数据
     */
    public static <T> T toJava(Message sourceMessage, Class<T> clazz) {
        if (sourceMessage != null) {
            try {
                return JSON.parseObject(JsonFormat.printer().includingDefaultValueFields().print(sourceMessage), clazz);
            } catch (InvalidProtocolBufferException e) {
                logger.error("ProtoMessage to JSON error:", e);
                throw new BusinessException(CommonEnum.DATA_CONVERSION_EXCEPTION);
            }
        }
        return null;
    }

    /**
     * 对象
     * JSON 转 proto 对象
     * 使用方法：Message message = ProtoJsonUtil.toObject(UserProto.User.newBuilder(), jsonObject);
     *
     * @param targetBuilder proto 对象 bulider
     * @param json          json 数据
     * @return 返回转换后的 proto 对象
     */
    public static Message toProtoMessage(Message.Builder targetBuilder, String json) {
        if (json != null) {
            //ignoringUnknownFields 如果 json 串中存在的属性 proto 对象中不存在，则进行忽略，否则会抛出异常
            try {
                JsonFormat.parser().ignoringUnknownFields().merge(json, targetBuilder);
            } catch (InvalidProtocolBufferException e) {
                logger.error("JSON to ProtoMessage error:", e);
                throw new BusinessException(CommonEnum.DATA_CONVERSION_EXCEPTION);
            }
            return targetBuilder.build();
        }
        return null;
    }



}
